from kivy.app import App
from kivy.metrics import sp
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty, ListProperty

from pypump.exception import PyPumpException
from goblinoid.config import feedsections as fs


class ActivityService(Widget):
    activity = ObjectProperty()
    activity_data = ListProperty([])

    def on_activity(self, instance, activity):
        if len(self.activity_data) == 0:
            self.activity_data = fs.mg_activity_dict(activity, 0)

    def get_comments(self):
        return self.activity.obj.comments

    def add_comment(self, comment_obj):
        self._update_activity_data_with_comment(comment_obj)
        try:
            self.activity.obj.comment(comment_obj)
        except PyPumpException, e:
            print (e)
            # pass for now
            pass

    # TODO: figure out why viewclass button is not being updated
    def _update_activity_data_with_comment(self, comment_obj):
        data_index = 0
        for item in self.activity_data:
            if item['viewclass'] == 'ViewCommentsButton':
                text = unicode(comment_obj.content)
                item['count'] += 1
                # Implies author is poster
                if comment_obj.author is None:
                    author = App.get_running_app().pump_service.pump.me
                else:
                    author = comment_obj.author
                formatted_comment = unicode(
                    '[ref=actor][color=86D4B1]{0}[/color][/ref] {1}'.format(
                        unicode(author.username), text))
                self.activity_data.insert(data_index+1, dict([
                    ("viewclass", "CommentSnapshot"),
                    ("actor", unicode(author)),
                    ("text", formatted_comment),
                    ("height", sp(20)),
                    ("markup", True)]))
                break
            data_index += 1

    def get_activity_data(self):
        if len(self.activity_data) == 0:
            self.activity_data = fs.mg_activity_dict(self.activity, 0)
        return self.activity_data

    def update_activity(self, activity):
        self.activity = activity

    def clear_activity_data(self):
        self.activity_data = []

    def start_prefetch(self, callback):
        callback(None)
